<!--
 * @Author: chenhuanhuan 2925102113@qq.com
 * @Date: 2024-12-16 16:29:00
 * @LastEditors: wuheng wuheng@szhbzc.com
 * @LastEditTime: 2025-03-04 20:35:42
 * @FilePath: \hbzc-groupmeal-center-web\src\centerViews\basicInformation\spuManage\spuInformation\components\matchSku.vue
-->
<template>

  <pb-popup v-model="isShow" :title="`${searchForm.spuName}-匹配SKU`" @cancelFn="offPopup" :showConfirm="false"
    Width="60%">

    <el-form label-width="auto" inline>
      <div class="position-relative">
        <el-form-item label="SKU名称">
          <pb-input v-model.trim="searchForm.skuName" @keyup.enter="getSpuMatchSkuApi"
            placeholder="请输入SKU名称"></pb-input>
        </el-form-item>
        <el-form-item label="SKU类别" prop="spuClassCode">
          <pb-tree-select v-model="searchForm.skuClassCode" :Data="skuTreeData" width="200"
            :defaultProps="{ children: 'children', label: 'skuClassName', value: 'skuClassCode' }"
            @change="getSpuMatchSkuApi" />
        </el-form-item>
        <el-form-item label="匹配状态：">
          <pb-check :list="statusList" @change="SetcostStatusFn($event)"></pb-check>
        </el-form-item>
        <div class="position-absolute right-0 top-0">
          <pb-button size="small" @click="getSpuMatchSkuApi">查询</pb-button>
        </div>
      </div>
    </el-form>

    <pb-table :column="skuColumn" :tableData="skuTableData" height="500px">
      <template #prior="{ row }">
        <pb-icon name="star-on" size="20" @click="onPurchasing(row)"
          :color="!row.isPriorityPurchasing ? variables['gary-color'] : variables['primary-color']"></pb-icon>
      </template>
      <template #operate="{ row }">
        <PopconfirmButton v-if="searchForm.status == 1" @confirm="deleteFn(row)"></PopconfirmButton>
        <PopconfirmButton v-else @confirm="deleteFn(row)" text="匹配"></PopconfirmButton>
      </template>
    </pb-table>
    <pb-pagination v-model:currentPage="pages.currentPage" v-model:pageSize="pages.pageSize" @onChange="onPagesChange"
      :total="pages.total"></pb-pagination>
  </pb-popup>

</template>

<script setup lang="ts">
import { getSkuClassTreeApi } from "@/utils/globalFn";
import { getPurchasingSpu } from '@/api/Sku'
import { deleteMatchSpu, getSpuMatchSku } from '@/api/Spu'
import { createMessage } from "@/Public-UIlibrary/pb-message/method";
import { createMsgBox } from '@/Public-UIlibrary/pb-message-box/method';
import variables from "@/styles/variables.module.scss";
import { skuMatchSpu } from '@/api/Sku'
const emits = defineEmits(['refresh'])
const SetcostStatusFn = (el: any) => {
  searchForm.value.status = el.val
  if (searchForm.value.status == 1) {
    skuColumn.value = Coulumn1()
  } else {
    skuColumn.value = Coulumn2()
  }
  getSpuMatchSkuApi()
  // console.log(searchForm.value, el, '222')
}
const isShow = ref(false)

const Coulumn1 = () => [
  {
    key: "skuClassName",
    name: "SKU类别",
  },
  {
    key: "skuName",
    name: "SKU名称",
  },
  {
    key: "brand",
    name: "品牌",
  },
  {
    key: "specifications",
    name: "规格",
  },
  {
    key: "accountingUnitName",
    name: "计量单位",
  },
  {
    slot: "prior",
    name: "优先采购",
    width: 100,
    align: 'center'
  },
  {
    slot: "operate",
    name: "操作",
    width: 100,
    align: 'right'
  }
]
const Coulumn2 = () => [
  {
    key: "skuClassName",
    name: "SKU类别",
  },
  {
    key: "skuName",
    name: "SKU名称",
  },
  {
    key: "brand",
    name: "品牌",
  },
  {
    key: "specifications",
    name: "规格",
  },
  {
    key: "accountingUnitName",
    name: "计量单位",
  },
  {
    slot: "operate",
    name: "操作",
    width: 100,
    align: 'right'
  }
]
const skuColumn = ref(Coulumn1());

const skuTableData = ref([])

const formOrigin = () => ({
  skuName: '',
  skuClassCode: '',
  spuName: '',
  spuCode: '',
  status: 1
})
const primatchListOrigin = () => [
  { label: "已匹配", val: 1, checked: true },
  { label: "未匹配", val: 0, checked: false }]
const statusList = ref(primatchListOrigin())
const searchForm = ref(formOrigin())

const pageInit = () => ({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});
const pages = ref(pageInit());
const onPagesChange = () => {
  getSpuMatchSkuApi()
};


const skuTreeData = ref([])
const showFn = (data) => {
  searchForm.value.status = 1
  statusList.value = primatchListOrigin()
  searchForm.value.skuName = ''
  searchForm.value.skuClassCode = ''
  searchForm.value.spuCode = data.spuCode
  searchForm.value.spuName = data.spuName
  skuColumn.value = Coulumn1()
  isShow.value = true

  getSkuClassTreeApi().then(res => {
    skuTreeData.value = res
    getSpuMatchSkuApi()
  })
}

const getSpuMatchSkuApi = () => {
  skuTableData.value = []
  let { currentPage, pageSize } = { ...pages.value };
  let { spuName, ...args } = { ...searchForm.value }
  let params = {
    currentPage, pageSize,
    ...args
  }
  getSpuMatchSku(params).then(res => {
    if (res.code == 2000) {
      skuTableData.value = res.data.records
      pages.value.total = res.data.total
    }
  })
}

const deleteFn = (row) => {
  if (searchForm.value.status == 1) {
    return new Promise<void>((resolve, reject) => {
      deleteMatchSpu({ skuCode: row.skuCode }).then(res => {
        if (res.code == 2000) {
          createMessage({
            message: '删除成功'
          })
          getSpuMatchSkuApi()
          emits('refresh')
        }
      })
    })
  } else {
    return new Promise<void>((resolve, reject) => {
      skuMatchSpu({ skuCode: row.skuCode, spuCode: searchForm.value.spuCode, unMatchOther: 0 }).then(res => {
        if (res.code == 2000) {
          if (res.data.matchedOtherSpu == 1) {
            createMsgBox(
              `是否更换绑定关系?`,
              { cancelText: '取消', showTitleIcon: false, confirmText: '确认', title: 'SKU存在', Width: 500, connectList: ['当前匹配为：' + res.data.matchedSpuName], showIcon: false }).then(res => {
                if (res) {
                  skuMatchSpu({ skuCode: row.skuCode, spuCode: searchForm.value.spuCode, unMatchOther: 1 }).then(ress => {
                    if (ress.code == 2000) {
                      createMessage({
                        message: '匹配成功'
                      })
                      getSpuMatchSkuApi()
                      emits('refresh')
                    }
                  })
                } else {
                }
              })
          } else {
            createMessage({
              message: '匹配成功'
            })
            getSpuMatchSkuApi()
            emits('refresh')
          }
        }
      })
    })
  }
}

// 设置优先
const onPurchasing = (row) => {
  return new Promise<void>((resolve, reject) => {
    getPurchasingSpu({ skuCode: row.skuCode }).then(res => {
      if (res.code == 2000) {
        createMessage({
          message: '设置成功'
        })
        getSpuMatchSkuApi()
      }
    })
  })
}
const offPopup = () => {
  isShow.value = false
  searchForm.value = formOrigin()
};

defineExpose({ showFn })
</script>



<style lang="scss" scoped>
::v-deep .el-form--inline .el-form-item {
  vertical-align: inherit
}
</style>
